﻿using Core;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Data.SqlClient;
using System.Data;

namespace DAL
{
    public class GroupInfoDAL : BaseDAL
    {
        #region 分组表导入
        /// <summary>
        /// 地区表导入
        /// </summary>
        /// <returns></returns>
        public bool GetGroupInfo()
        {
            Func<int, bool> DownGroupInfo = (roomid) =>
            {
                using (WebClient wc = new WebClient())
                {
                    wc.Encoding = System.Text.Encoding.GetEncoding("utf-8");
                    string strGi = string.Empty;
                    try
                    {
                        strGi = wc.DownloadString(ConfigHelper.GetConfigString("RemoteUrl") + "/Ayyfford/GetGroupInfoByRoomID/" + roomid);
                    }
                    finally
                    {
                        wc.Dispose();
                    }
                    if (!string.IsNullOrWhiteSpace(strGi))
                    {
                        var lGi = JsonConvert.DeserializeObject<List<Model.GroupInfo>>(strGi);

                        #region 数据入库
                        using (var conn = new SqlConnection(connection))
                        {
                            conn.Open();
                            IDbTransaction transaction = conn.BeginTransaction();
                            try
                            {
                                lGi.ForEach(gi =>
                                {
                                    conn.Execute("if not exists (select ID from GroupInfo where ID=" + gi.ID + @")  
                                                begin 
                                                    insert into GroupInfo(ID,TeacherId,ClassId,GroupName,StuId,Leader) values (@ID,@TeacherId,@ClassId,@GroupName,@StuId,@Leader)
                                                end
                                                    else
                                                begin
                                                    update GroupInfo set TeacherId=@TeacherId,ClassId=@ClassId,GroupName=@GroupName,StuId=@StuId,Leader=@Leader where ID=@ID
                                                end", gi, transaction);
                                });
                                transaction.Commit();
                                lGi.ForEach(gi =>
                                {
                                    WebClient wcTmp = new WebClient();
                                    wcTmp.Encoding = System.Text.Encoding.GetEncoding("utf-8");
                                    string _result = wcTmp.DownloadString(string.Format(ConfigHelper.GetConfigString("RemoteUrl") + "/Ayyfford/DelAsyncExtID/{0}?rid={1}&tp={2}", ConfigHelper.GetConfigInt("RoomID"), gi.ID, 1));
                                    wcTmp.Dispose();
                                    if (_result.ToString().ToLower() != "true")
                                    {
                                        Log.errorlog(new Exception("删除已完成同步的分组数据！"));
                                    }
                                });
                                return true;
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                Log.errorlog(ex);
                            }
                            conn.Close();
                        }
                        #endregion
                    }
                }
                return false;
            };

            var RoomIds = ConfigHelper.GetConfigString("RoomID").Split(',');
            if (RoomIds.Length > 0)
            {
                int _rid = 0;
                bool iscompalted = true;
                foreach (var rid in RoomIds)
                {
                    if (int.TryParse(rid, out _rid) && _rid > 0)
                    {
                        iscompalted = iscompalted && DownGroupInfo(_rid);
                    }
                }
                return iscompalted;
            }

            return false;
        }
        #endregion

        #region 分组表删除
        /// <summary>
        /// 分组表删除
        /// </summary>
        /// <returns></returns>
        public bool DelGroupInfo()
        {
            Func<int, bool> DelGroupInfo = (roomid) =>
            {
                using (WebClient wc = new WebClient())
                {
                    wc.Encoding = System.Text.Encoding.GetEncoding("utf-8");
                    string strGids = string.Empty;
                    try
                    {
                        strGids = wc.DownloadString(ConfigHelper.GetConfigString("RemoteUrl") + "/Ayyfford/GetDelGroupInfoByRoomID/" + roomid);
                        if (string.IsNullOrWhiteSpace(strGids))
                            return false;
                    }
                    finally
                    {
                        wc.Dispose();
                    }
                    if (!string.IsNullOrWhiteSpace(strGids))
                    {
                        #region 数据入库
                        using (var conn = new SqlConnection(connection))
                        {
                            try
                            {
                                conn.Open();
                                conn.Execute("delete GroupInfo where ID in(" + strGids + ")");
                                conn.Close();
                                var gids = strGids.Split(',');
                                foreach (var gid in gids)
                                {
                                    WebClient wcTmp = new WebClient();
                                    wcTmp.Encoding = System.Text.Encoding.GetEncoding("utf-8");
                                    string _result = wcTmp.DownloadString(string.Format(ConfigHelper.GetConfigString("RemoteUrl") + "/Ayyfford/DelAsyncExtID/{0}?rid={1}&tp={2}", roomid, gid, 2));
                                    wcTmp.Dispose();
                                    if (_result.ToString().ToLower() != "true")
                                    {
                                        Log.errorlog(new Exception("删除已完成同步的分组数据！"));
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Log.errorlog(ex);
                            }
                            finally
                            {
                                conn.Close();
                            }
                        }
                        #endregion
                    }
                    return false;
                }
            };
            var RoomIds = ConfigHelper.GetConfigString("RoomID").Split(',');
            if (RoomIds.Length > 0)
            {
                int _rid = 0;
                bool iscompalted = true;
                foreach (var rid in RoomIds)
                {
                    if (int.TryParse(rid, out _rid) && _rid > 0)
                    {
                        iscompalted = iscompalted && DelGroupInfo(_rid);
                    }
                }
                return iscompalted;
            }
            return false;
        }
        #endregion
    }
}
